# ~*~ coding: utf-8 ~*~
import time
from sqlalchemy.dialects.mysql import TINYINT

from apps.common.dbbase import BaseModel
from apps.common.utils import generate_uuid, get_signer
from apps.extensions import db

signer = get_signer()


class Permission(BaseModel):
    __tablename__ = 'perms_permission'

    id = db.Column(db.CHAR(36), default=generate_uuid, primary_key=True)
    module = db.Column(db.VARCHAR(128), nullable=True)
    controller = db.Column(db.VARCHAR(128), nullable=True)
    action = db.Column(db.VARCHAR(128), nullable=True)

    pid = db.Column(db.CHAR(36), nullable=True)
    name = db.Column(db.VARCHAR(255), nullable=False, unique=True)
    is_menu = db.Column(TINYINT, nullable=False, default=0)  # 0：否, 1: 是
    icon = db.Column(db.VARCHAR(255), nullable=True)
    sort = db.Column(db.INT, nullable=False, default=0)

    create_time = db.Column(db.INT, default=time.time)
    update_time = db.Column(db.INT, default=time.time, onupdate=time.time)

    def __str__(self):
        return "<Permission:{}>".format(self.name)


class Role(BaseModel):
    __tablename__ = 'perms_role'

    id = db.Column(db.CHAR(36), default=generate_uuid, primary_key=True)
    name = db.Column(db.VARCHAR(255), nullable=False, unique=True)
    describe = db.Column(db.VARCHAR(255), default='')

    create_time = db.Column(db.INT, default=time.time)
    update_time = db.Column(db.INT, default=time.time, onupdate=time.time)

    def __str__(self):
        return "<Role:{}>".format(self.name)


class RolePermission(BaseModel):
    __tablename__ = 'perms_role_permission'

    id = db.Column(db.CHAR(36), default=generate_uuid, primary_key=True)
    permission_id = db.Column(db.CHAR(36))
    role_id = db.Column(db.CHAR(36))

    create_time = db.Column(db.INT, default=time.time)
    update_time = db.Column(db.INT, default=time.time, onupdate=time.time)

    def __str__(self):
        return "<RolePermission:{}>".format(self.id)


class UserRole(BaseModel):
    __tablename__ = 'perms_user_role'

    id = db.Column(db.CHAR(36), default=generate_uuid, primary_key=True)
    user_id = db.Column(db.CHAR(36))
    role_id = db.Column(db.CHAR(36))

    create_time = db.Column(db.INT, default=time.time)
    update_time = db.Column(db.INT, default=time.time, onupdate=time.time)

    def __str__(self):
        return "<UserRole:{}>".format(self.id)
